<template>
	<div
		class="table-control-search-container"
		:style="{ height: props.isShowSearch ? state.rowHeight + 'px' : '0' }"
	>
		<el-form
			ref="tableSearchRef"
			class="table-form"
			:model="state.ruleForm"
			:size="themeConfig.globalComponentSize"
			label-width="auto"
		>
			<el-row id="table-control-search-row" :gutter="12">
				<template v-for="val in props.tableSearch">
					<el-col
						v-if="!val.isHide"
						:key="val.prop"
						:xs="24"
						:sm="12"
						:md="val.type.includes('multi') || val.type.includes('Range') ? 12 : 8"
						:lg="val.type.includes('multi') || val.type.includes('Range') ? 8 : 6"
						:xl="val.type.includes('multi') || val.type.includes('Range') ? 6 : 4"
						class="mb10"
					>
						<el-form-item
							:label="val.label"
							:prop="val.prop"
							:rules="[
								{
									required: val.required,
									message: `${val.label}不能为空`,
									trigger: val.type === 'input' ? 'blur' : 'change',
								},
							]"
						>
							<el-input
								v-if="val.type === 'input'"
								v-model="state.ruleForm[val.prop]"
								:placeholder="val.placeholder"
								clearable
								style="width: 100%"
							/>
							<el-input-number
								v-else-if="val.type === 'number'"
								v-model="state.ruleForm[val.prop]"
								:placeholder="val.placeholder"
								:min="val.min"
								:max="val.max"
								:step="val.step"
								:precision="val.precision"
								style="width: 100%"
							/>
							<el-select
								v-else-if="val.type === 'select'"
								v-model="state.ruleForm[val.prop]"
								:placeholder="val.placeholder"
								clearable
								style="width: 100%"
							>
								<el-option
									v-for="item in val.options"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								>
								</el-option>
							</el-select>
							<el-select
								v-else-if="val.type === 'multiSelect'"
								v-model="state.ruleForm[val.prop]"
								:placeholder="val.placeholder"
								multiple
								clearable
								style="width: 100%"
							>
								<el-option
									v-for="item in val.options"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								>
								</el-option>
							</el-select>
							<el-tree-select
								v-else-if="val.type === 'treeSelect'"
								v-model="state.ruleForm[val.prop]"
								:placeholder="val.placeholder"
								:data="val.options || []"
								:props="
									val.treeProps || {
										label: 'label',
										value: 'id',
										children: 'children',
										disabled: 'disabled',
									}
								"
								:check-strictly="val.isCheckStrictly"
								:filter-node-method="(value: string, data: EmptyObjectType) => filterTreeNode(value, data, val.treeProps)"
								filterable
								clearable
								node-key="id"
								style="width: 100%"
							/>
							<el-date-picker
								v-else-if="val.type === 'date'"
								v-model="state.ruleForm[val.prop]"
								:placeholder="val.placeholder"
								type="date"
								style="width: 100%"
							/>
							<el-time-picker
								v-else-if="val.type === 'time'"
								v-model="state.ruleForm[val.prop]"
								:placeholder="val.placeholder"
								style="width: 100%"
							/>
							<el-cascader
								v-else-if="val.type === 'cascader'"
								v-model="state.ruleForm[val.prop]"
								:options="val.options || []"
								:props="{
									expandTrigger: 'hover',
									value: 'value',
									label: 'label',
									children: 'children',
								}"
								:placeholder="val.placeholder"
								filterable
								clearable
								style="width: 100%"
							/>
							<el-date-picker
								v-else-if="val.type === 'datetime'"
								v-model="state.ruleForm[val.prop]"
								:placeholder="val.placeholder"
								type="datetime"
								style="width: 100%"
							/>
							<el-date-picker
								v-else-if="val.type === 'dateRange'"
								v-model="state.ruleForm[val.prop]"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								type="daterange"
								style="width: 100%"
							/>
							<el-time-picker
								v-else-if="val.type === 'timeRange'"
								v-model="state.ruleForm[val.prop]"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
								is-range
								style="width: 100%"
							/>
							<el-date-picker
								v-else-if="val.type === 'datetimeRange'"
								v-model="state.ruleForm[val.prop]"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
								type="datetimerange"
								style="width: 100%"
							/>
							<el-rate
								v-else-if="val.type === 'rate'"
								v-model="state.ruleForm[val.prop]"
								:colors="['#99A9BF', '#F7BA2A', '#FF9900']"
								size="default"
								clearable
								allow-half
								show-score
								score-template="{value} 星"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>
				</template>
				<el-col :xs="12" :sm="6" :md="6" :lg="4" :xl="4" class="mb10">
					<div class="">
						<el-button type="primary" @click="onSearch(tableSearchRef)">查询</el-button>
						<el-button type="info" @click="onReset(tableSearchRef)">重置</el-button>
					</div>
				</el-col>
			</el-row>
		</el-form>
	</div>
</template>

<script setup lang="ts" name="tableControlSearch">
import { reactive, ref, onMounted, watch } from "vue";
import type { FormInstance } from "element-plus";
import { storeToRefs } from "pinia";
import { useThemeConfig } from "/@/stores/themeConfig";

// 定义父组件传过来的值
interface TableControlSearchProps {
	tableSearch: TableSearchType[]; // 搜索表单配置项
	isShowSearch?: boolean; // 是否显示搜索栏
}
const props = withDefaults(defineProps<TableControlSearchProps>(), {
	isShowSearch: false,
});

// 定义父组件可触发的事件
const emit = defineEmits(["search"]);

// 定义变量内容
const { themeConfig } = storeToRefs(useThemeConfig());
const tableSearchRef = ref<FormInstance>();
const state = reactive({
	ruleForm: {},
	rowHeight: 0,
});

// 查询
const onSearch = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (valid) {
			emit("search", JSON.parse(JSON.stringify(state.ruleForm)));
		}
	});
	console.log("onSearch", state.ruleForm);
};
// 重置
const onReset = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	emit("search", state.ruleForm, true);
};
// treeSelect 过滤方法
const filterTreeNode = (value: string, data: EmptyObjectType, treeProps?: EmptyObjectType) => {
	if (!value) return true;
	return data[treeProps?.label || "label"].includes(value);
};
// 初始化 form 字段
const initFormField = () => {
	if (props.tableSearch.length === 0) return;
	props.tableSearch.filter(v => !v.isHide).forEach(v => (state.ruleForm[v.prop] = v.defaultValue || ""));
};
// 页面加载时
onMounted(() => {
	initFormField();
});
// 监听 props.isShowSearch 变化，动态获取元素 el-row 的高度
watch(
	() => props.isShowSearch,
	() => {
		const tableRowElement = document.querySelector("#table-control-search-row");
		if (tableRowElement) state.rowHeight = tableRowElement.clientHeight;
	},
	{ immediate: true }
);
</script>

<style scoped lang="scss">
.table-control-search-container {
	flex-shrink: 0;
	display: flex;
	overflow: hidden;
	transition: height 0.25s ease-in-out;
	.table-form {
		flex: 1;
	}
}
</style>
